package com.etlmaster.executor.steps.sql;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.DpExecutorUtils;
import com.etlmaster.executor.utils.StepState;
import com.etlmaster.jdbc.JdbcTemplate;
/**
 * @author Wugf
 * @date 2016-03-08
 */
public class CheckPartitionProcessor {
	private String checkPartition;
	private JdbcTemplate jdbc;
	private String partition;
	private CheckPartitionExistStepMeta meta;
	private int init(CheckPartitionExistStepMeta meta){
		this.meta=meta;
		checkPartition=DataCollectionUtils.getProperties("checkPartition");
		Map<String,Object> dbInfo=new HashMap<String,Object>();
		if(checkPartition!=null&&checkPartition!=""){ 
			partition=meta.getPartition();
			//dbInfo=DataCollectionUtils.fetchDBUserInfoByTeam(meta.getDsName(), meta.getJobMeta().getTeamCode(), new JdbcTemplate());
			dbInfo.put("tableName", meta.getTableName());
			dbInfo.put("partition", meta.getPartition());
			checkPartition=DpExecutorUtils.variableSubstitution(checkPartition, dbInfo);
			jdbc=new JdbcTemplate(meta.getDsName());
		}else{
			meta.log("ERROR","未设置查询分区语句，请检查配置文件");
			return StepState.RUNNING_FAILED;
		}
		return StepState.RUNNING_SUCCESSED;
	}
	private int query(){
		try{
			meta.log("INFO","查询分区信息：",checkPartition);
			List<Map<String,Object>> list=jdbc.queryForList(checkPartition);
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("partition", partition);
			if(list.contains(map)){
				meta.log("INFO","查询到表:{},分区：{}的信息 ",meta.getTableName(),meta.getPartition());
				return StepState.RUNNING_SUCCESSED;
			}
			else{
				meta.log("WARN","未查询到表:{},分区：{}的信息",meta.getTableName(),meta.getPartition());
				return StepState.RUNNING_FAILED;
			}
		}catch(Exception e){
			meta.log("ERROR","查询分区信息失败，{}",e.getMessage());
			return StepState.RUNNING_FAILED;
		}
	}
	public int process(CheckPartitionExistStepMeta meta){
		return init(meta)+query();
	}

}
